/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-01-08 14:24:33
 * @LastEditors: LIFM0623 1944099171@qq.com
 * @LastEditTime: 2024-02-29 19:23:11
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-02-22 20:33:13
 * @FilePath: \Scene_Back\src\auth\jwt.strategy.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ConfigService } from '@nestjs/config';
import { UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { StrategyOptions, Strategy, ExtractJwt } from 'passport-jwt';
import { AuthService } from './auth.service';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/user/entities/user.entity';

export class JwtStorage extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly configService: ConfigService,
    private readonly authService: AuthService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get('SECRET', 'yssyyds'),
    } as StrategyOptions);
  }
  
  async validate(payload: User) {
    const existUser = await this.authService.getUser(payload);
    if (!existUser) {
      throw new UnauthorizedException(); // 或者返回一个包含 status 和 message 的对象
    }
    return existUser;
  }
}
